package utils

import (
	"os"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
)

var Logger *zap.Logger

// InitLogger 初始化日志记录器
func InitLogger(env string) error {
	var config zap.Config

	if env == "prod" {
		// 生产环境配置
		config = zap.NewProductionConfig()
		config.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
	} else {
		// 开发环境配置
		config = zap.NewDevelopmentConfig()
		config.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
	}

	// 日志文件输出
	fileWriter := zapcore.AddSync(&lumberjack.Logger{
		Filename:   "logs/app.log",
		MaxSize:    100, // MB
		MaxBackups: 30,
		MaxAge:     30, // days
		Compress:   true,
	})

	// 控制台输出
	consoleWriter := zapcore.AddSync(os.Stdout)

	core := zapcore.NewTee(
		zapcore.NewCore(
			zapcore.NewJSONEncoder(config.EncoderConfig),
			fileWriter,
			config.Level,
		),
		zapcore.NewCore(
			zapcore.NewConsoleEncoder(config.EncoderConfig),
			consoleWriter,
			config.Level,
		),
	)

	Logger = zap.New(core, zap.AddCaller())
	return nil
}

// SyncLogger 同步日志缓冲区
func SyncLogger() {
	_ = Logger.Sync()
}
